﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Phatent.Model.Pages;
namespace Phatent.Command.Pages
{
    public class MessageCommand
    {
        public static MessageModel CreateNewMessage(MessageModel model)
        {
            if (model != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    model.CreatedOn = DateTime.Now;
                    var d = Convertor.ConvertFrom<Message, MessageModel>(model);
                    db.DataContext.Messages.Add(d);
                    db.DataContext.SaveChanges();
                    model.ID = d.ID;
                    return model;
                }
            }
            return null;
        }

        public static void Delete(int id)
        {
            if (id > 0)
            {
                using (DBCentre db=new DBCentre())
                {
                    db.Delete<Message>(p => p.ID == id);
                    db.DataContext.SaveChanges();
                }
            }
        }

        public static MessageCollection Gets(MessageQuery sea)
        {
            var ret = new MessageCollection();
            using (DBCentre db = new DBCentre())
            {
                IQueryable<Message> q = db.DataContext.Messages;
                var n = q.Count();
                if (n > 0)
                {
                    q = q.OrderByDescending(p => p.ID);
                    if (sea != null && sea.PageSize > 0)
                        q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                    var lst = q.ToList();
                    ret = Convertor.ConvertCollection<MessageModel, Message, MessageCollection>(lst);
                    ret.TotalRecordsCount = n;
                }
            }
            return ret;
        }
    }
}
